from flask import Flask, request
from main import *

app = Flask(__name__, static_folder='public', static_url_path='')


# 允许跨域访问
@app.after_request
def after_request(response):
    # 允许跨域访问
    response.headers['Access-Control-Allow-Origin'] = '*'
    # 允许跨域访问的请求方法
    response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
    # 允许跨域访问的请求头
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
    return response


@app.route('/', methods=['GET'])
def get_index():
    return app.send_static_file('index.html')


@app.route('/open-serial', methods=['GET'])
def get_open_serial():
    # 在这里调用打开串口的函数
    try:
        success = open_serial()
    except:
        success = False
        print('Error: 打开串口失败，请检查串口地址是否正确')
    return {
        'success': success
    }


@app.route('/config', methods=['GET'])
def get_config():
    # 获取请求参数
    key = request.args.get('key')
    value = request.args.get('value')
    if key and value:
        if not key in config:
            return {
                'success': False
            }
        if key != 'port':
            if key != 'timeout' and key != 'ask_interval':
                value = int(value)
            else:
                value = float(value)
        print(f'key: {key}, value: {value}')
        config[key] = value
    return {
        'success': True,
        'config': config
    }


@app.route('/check', methods=['GET'])
def get_check():
    id = int(request.args.get('id'))
    if not id:
        print('Error: 设备id为空')
        return {
            'success': False
        }, 500
    try:
        success = check_device(id)
    except:
        success = False
        print('Error: 检查设备时错误，请检查是否成功打开了串口')
    return {
        'success': success
    }


@app.route('/score', methods=['GET'])
def get_score():
    id = int(request.args.get('id'))
    if not id:
        print('Error: 设备id为空')
        return {
            'success': False
        }, 500
    score = -1
    try:
        score = get_device_score(id)
        success = True
    except:
        success = False
        print('Error: 获取分数时错误，请检查是否成功打开了串口或设备是否存在')
    return {
        'success': success,
        'score': score
    }


@app.route('/reset', methods=['GET'])
def get_reset():
    success = True
    try:
        reset_device()
    except:
        success = False
        print('Error: 重置失败，请检查是否成功打开了串口')
    return {
        'success': success
    }


if __name__ == '__main__':
    app.run(host='0.0.0.0')
